<?php
namespace Infinity;

class Node extends \Infinity\AbstractEntity {
    private static $_instance = null;
    
    protected function init() {
        $this->setEntityType('node');
    }

    public static function create() {
        return new self(array(
            'type' => '',
            'title' => '<none>',
            'uid' => $GLOBALS['user']->uid,
            'status' => 0,
            'language' => LANGUAGE_NONE
        ));
    }

    public static function load($id) {
        if(is_array($id)) {
            $ids = $id;
            $entities = array();
            foreach($ids as $_id) {
                $self = new self($_id);
                if(!$self->isEmpty()) {
                    $entities []= $self;
                }
            }
            return $entities;
        } else
            $self = new self($id);
            if(!$self->isEmpty())
                return $self;
            else
                return false;
    }
    
    public static function getInstance($id) {
        if (is_null ( self::$_instance ) || isset ( self::$_instance )) {
            self::$_instance = new self($id);
        }
        return self::$_instance;
    }

    /**
     * 从一个对象复制出entity
     * @param $entity_type
     * @param $entity
     * @return Entity
     */
    public static function createDuplicate($entity_type, $entity) {
        $entity->nid = NULL;
        $entity->vid = NULL;
        $entity->tnid = NULL;
        $entity->uid = $GLOBALS['user']->uid;
        $entity->created = time();
        $entity->updated = NULL;
        return new Node($entity_type, $entity);
    }
    
    public static function asJson($nodes, $view_mode=''){
        $results = array();
        foreach($nodes as $node) {
            if($view_mode)
                $node->view = drupal_render(node_view($node, $view_mode));
            unset($node->data);
            $results[]= $node;
        }
        return json_encode($results);
    }
}